package com.github.grpc.server.configuration;

import com.github.grpc.server.property.EtcdRegister;
import com.github.grpc.server.property.GrpcServerProperties;
import com.github.grpc.server.utils.InetAddressUtil;
import mousio.etcd4j.EtcdClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@AutoConfigureAfter(EtcdRegisterConfiguration.class)
@EnableConfigurationProperties(GrpcServerProperties.class)
@Import(EtcdAutoConfiguration.class)
public class GrpcRegisterConfiguration {

    private static final Logger log = LoggerFactory.getLogger(GrpcRegisterConfiguration.class);

    @Bean
    @ConditionalOnMissingBean
    public EtcdRegister etcdRegister(EtcdClient etcdClient, GrpcServerProperties grpcServerProp) {
        EtcdRegister etcdRegister = new EtcdRegister();
        etcdRegister.setClient(etcdClient);

        String ip = InetAddressUtil.getLocalHostLanAddress().getHostAddress();
        String address = ip + ":" + String.valueOf(grpcServerProp.getPort());

        log.info("register grpc service to etcd.");
        log.info("grpc server address: {}", address);

        etcdRegister.setKey(address);
        etcdRegister.setValue(address);
        etcdRegister.setPath(grpcServerProp.getPath());
        etcdRegister.setStart(grpcServerProp.isRegister());

        return etcdRegister;
    }

}
